import {iMicroConfig} from "@peryl/micro-web";
import {$loading} from "plain-design";
import {createHooks, delay, onBeforeUnmount} from "@peryl/react-compose";
import {createEffects} from "@peryl/utils/createEffects";

export function useMicroLoading(microConfig: iMicroConfig) {
  const state = { errors: {} as Record<string, string | undefined> };
  const closeLoading = $loading();
  onBeforeUnmount(microLoadingHook.use(({ id, error }) => {
    if (id === microConfig.id) {
      /*关闭loading*/
      delay(78).then(closeLoading);
      /*将错误保存起来，下次再打开子应用页面的时候拿这个错误出来展示*/
      state.errors[microConfig.id] = typeof error === "string" ? error : JSON.stringify(error);
    }
  }));
  onBeforeUnmount(closeLoading);
  return state;
}

export const microLoadingHook = createHooks<(data: { id: string, error?: string | null | undefined }) => void>(createEffects().effects);
